﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Obra.Common;

namespace Obra.Test
{
    public static class TestHelper
    {
        /// <summary>
        /// Get the data returned by issuing a GET of the specified URL.
        /// </summary>
        public static string Fetch(Uri uri)
        {
            WebClient client = new WebClient();

            return Encoding.UTF8.GetString(
                client.DownloadData(uri));
        }

        public static string CreateTempDirectory()
        {
            string directory = Path.Combine(
                Path.GetTempPath(),
                Path.GetRandomFileName());

            Directory.CreateDirectory(directory);
            return directory;
        }
       
        public static string CreateRandomFileWithExtension(
            string directory,
            string extension)
        {
            string filename = Path.Combine(
                directory,
                TestHelper.RandomFileNameWithExtension(extension));

            TestHelper.CreateTempFile(filename);
            return filename;
        }

        public static string RandomFileNameWithExtension(
            string extension)
        {
            string filename = Path.ChangeExtension(
                Path.GetRandomFileName(),
                extension);
            
            return filename;
        }

        public static void CreateTempFile(
            string path)
        {
            File.WriteAllText(path, String.Empty);
        }

        public static string WriteRandomDataToFile(
            string filename,
            ChecksumAlgorithm checksumAlgorithm)
        {
            File.WriteAllText(filename, Guid.NewGuid().ToString());
            using (FileStream stream = new FileStream(filename, FileMode.Open))
            {
                return new Checksum(stream, checksumAlgorithm).ToString();
            }
        }

        public static void DeleteFile(string filename)
        {
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }
        }

        public static string ComputeMD5ChecksumOfString(
           string data)
        {
            Obra.Common.Checksum checksum = new Obra.Common.Checksum(
                data,
                Obra.Common.ChecksumAlgorithm.MD5);

            return checksum.ToString();
        }

        public static Stream GetStreamFromString(
            string data)
        {
            return new MemoryStream(Encoding.UTF8.GetBytes(data));
        }
    }
}
